#pragma once

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include "Log.hpp"
#include "Cond.hpp"
#include "Thread.hpp"
#include "Mutex.hpp"

namespace ThreadPoolModule
{
    using namespace ThreadModlue;
    using namespace LogModule;
    using namespace CondModule;
    using namespace MutexModule;

    static const int gnum = 5; // 预创建5个线程
    template <class T>
    class ThreadPool
    {
    private:
        ThreadPool(int num = gnum)
            : _num(num), _isrunning(false)
        {
            for (int i = 0; i < _num; i++)
            {
                _threads.emplace_back(
                    [this]()
                    {
                        HandlerTask();
                    });
            }
        }

        ~ThreadPool() {}

        // 删除拷贝构造函数和赋值运算符
        ThreadPool(const ThreadPool&) = delete;
        ThreadPool& operator=(const ThreadPool&) = delete;

        void Start()
        {
            if (_isrunning)
                return;
            _isrunning = true;
            for (auto &thread : _threads)
            {
                thread.Start();
                LOG(LogLevel::INFO) << "new thread start: " << thread.Name();
            }
        }

        void HandlerTask()
        {
            char name[128];
            pthread_getname_np(pthread_self(), name, sizeof(name));
            while (true)
            {
                T t;
                {
                    LockGuard lockguard(_mutex);
                    // 队列为空, 或者线程池没有退出，我们才需要wait
                    while (_taskq.empty() && _isrunning)
                    {
                        _sleepernum++;
                        _cond.Wait(_mutex);
                        _sleepernum--;
                    }

                    // 线程被唤醒
                    // 判断线程池是否退出——如果线程池要退出，并且任务队列为空就退出
                    if (!_isrunning && _taskq.empty())
                    {
                        LOG(LogLevel::INFO) << name << "退出了，线程池想退出且任务队列为空";
                        break;
                    }

                    // 从任务队列中取任务
                    t = _taskq.front();
                    _taskq.pop();
                }
                // 处理任务，不需要在临界区内部，为什么？
                t();
            }
        }

        void WakeUpAllThread()
        {
            LockGuard lockguard(_mutex);
            if (_sleepernum)
            {
                _cond.Broadcast();
                LOG(LogLevel::INFO) << "唤醒所有线程";
            }
        }

    public:
        static ThreadPool<T>* GetInstance()
        {
            if(_inst == nullptr)
            {
                LockGuard lockguard(_lock);
                LOG(LogLevel::DEBUG) << "获取单例...";
                if(_inst == nullptr)
                {
                    LOG(LogLevel::DEBUG) << "首次使用，创建单例...";
                    _inst = new ThreadPool<T>();
                    _inst->Start();
                }
            }
            return _inst;
        }

        void Stop()
        {
            if (!_isrunning)
                return;
            _isrunning = false;
            // 唤醒所有线程
            WakeUpAllThread();
        }

        void Join()
        {
            for(auto& thread : _threads)
            {
                thread.Join();
            }
        }

        bool Enqueue(const T& in)
        {
            LockGuard lockguard(_mutex);
            // 如果线程池退出就不能再将任务入队列
            if(_isrunning)
            {
                _taskq.push(in);
                // 有线程在休眠，就唤醒
                if(_sleepernum > 0)
                {
                    _cond.Signal();
                }
                return true;
            }
            return false;
        }
    private:
        std::vector<Thread> _threads; // 管理线程
        int _num;                     // 线程的数量
        std::queue<T> _taskq;         // 任务队列
        Cond _cond;
        Mutex _mutex;

        bool _isrunning; // 运行标志位
        int _sleepernum; // 线程休眠的数量

        static ThreadPool<T>* _inst; // 单例指针
        static Mutex _lock;
    };

    // 静态成员类外初始化
    template<class T>
    ThreadPool<T>* ThreadPool<T>::_inst = nullptr;

    template<class T>
    Mutex ThreadPool<T>::_lock;
}